import { defineStore } from "pinia";
import request from '@/utils/request'
import { ApiResObj } from '@/types/data'
import { Profile } from '@/types/user'
import { getProfile, setProfile, removeProfile } from "@/utils/storage";
import useStore from "..";
export default defineStore('user', {
  state() {
    return {
      //登录的相关信息
      profile: getProfile() as Profile,
      query:''
    }
  },
  actions: {
    // 账户+密码 发送登录请求 账号+密码
    async login(obj: { account: string, password: string }) {
      const res = await request.post<ApiResObj<Profile>>('/login', obj)
      // console.log(res.data.result);
      this.profile = res.data.result
      setProfile(res.data.result)
      const { cart } = useStore()
      cart.mergeCart()
    },

    //手机号+验证码 发送请求
    async mobileLogin(mobile: string, code: string) {
      const res = await request.post<ApiResObj<Profile>>('/login/code', { mobile, code })
      this.profile = res.data.result
      setProfile(res.data.result)
      const { cart } = useStore()
      cart.mergeCart()
    },

    //校验openId
    async qqLogin(unionId: string, source: number = 6) {
      const res = await request.post<ApiResObj<Profile>>('/login/social', { unionId, source })
      // console.log(res);
      this.profile = res.data.result
      setProfile(res.data.result)
      const { cart } = useStore()
      cart.mergeCart()
    },
    //--绑定已有账号发送验证码
    // 绑定qq的短信验证码
    async sendQQBindMsg(mobile: string) {
      await request.get('/login/social/code', {
        params: {
          mobile
        }
      })
    },

    //已有手机号绑定
    async qqBindLogin(openId: string, mobile: string, code: string) {
      const res = await request.post<ApiResObj<Profile>>('/login/social/bind', {
        mobile,
        code,
        unionId: openId
      })
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
      const { cart } = useStore()
      cart.mergeCart()
    },

    // 获取短信验证码
    // 绑定qq的短信验证码
    async sendQQPathMsg(mobile: string) {
      await request.get('/register/code', {
        params: {
          mobile
        }
      })
    },

    //完善资料登录  没有手机账号 也没有qq记录
    async qqPatchLogin(data: any) {
      const res = await request.post<ApiResObj<Profile>>(
        `/login/social/${data.openId}/complement`,
        data
      )
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
      const { cart } = useStore()
      cart.mergeCart()
    },

    //携带手机号获取验证码
    async getCode(mobile: string) {
      await request.get('/login/code', { params: { mobile } })
    },

    //退出登录
    logout() {
      const { cart } = useStore()
      //清除本地个人信息
      removeProfile()
      //清除pinia中信息
      // setProfile({} as Profile)
      this.profile = {} as Profile
      //清空购物车
      cart.clearCart()
    },
  }
})